# -*- coding:utf-8 -*-

# /*拼多多评价信息*/

import requests,time
from config import *
from helper import Helper
from random import randint

class PddComments( object ):

    def __init__(self):

        # self.page = 0
        pass


    # 页面请求
    def requestIndex(self,task):

        print('======>',task)

        # page页码
        page = 1
        #
        while True:

            try:

                data = {"pageSize":10,"pageNo":page,"status":0,"startTime":Helper.changeTimeStamp(task['t_start_time']),"endTime":Helper.changeTimeStamp(task['t_end_time'])}

                header['cookie'] = task['cookie']

                print('*---------------------------------正在请求第%d页-----------------------------------*'%page)
                r = requests.post(url=domain_url['comments_url'],headers=header,data=json.dumps(data) )
                # print( r.json())

                if r.status_code == 200 and '会话已过期' in json.dumps(r.json(),ensure_ascii=False):

                    print('COOKIE已经过期')

                    data = {

                        "zhanghao": task["account"],
                        "dianpuming": task["shop_name"],
                        "Cookie": ""
                    }

                    data = json.dumps(data)

                    # Helper.returnCookieTask(data)

                    # 任务失败

                    # 如果不为真返回任务失败
                    data = json.dumps({
                        "caijiwancheng": [{
                            "pingjiashijian": "",
                            "descScore": "",
                            "logisticsScore": "",
                            "serviceScore": "",
                            "dingdanhao": "",
                            "task_id": task['id'],
                            "state": "3",
                            "shop_id": task['shop_id']
                        }]
                    })

                    Helper.returnCommentTask(data)

                    # 返回任务失败
                    return False

                elif r.status_code == 200 and not r.json()['result']:

                    print('此页数无任何评价信息')

                    # 返回任务采集成功
                    data = json.dumps({
                        "caijiwancheng": [{
                            "pingjiashijian": "",
                            "descScore": "",
                            "logisticsScore": "",
                            "serviceScore": "",
                            "dingdanhao": "",
                            "task_id": task['id'],
                            "state": "2",
                            "shop_id": task['shop_id']
                        }]
                    })

                    Helper.returnCommentTask(data)

                    return False

                elif r.status_code == 200 and r.json()['result']:

                    items = r.json()['result']['data']

                    self.parseIndex ( items ,task )
                    # 不满足十条评价跳出循环
                    if len( items ) < 10:

                        break

                page += 1

                time.sleep( randint(4,8))

            except Exception as e:

                # 记录错误信息
                # task.pop('cookie')
                Helper.writeErrorLog( task )

                print( e )

                break


    # 解析信息
    def parseIndex(self,items,task):

        for item in items:

            data = {
                "caijiwancheng": [{
                    # 评价时间
                    "pingjiashijian": item['createTime'],
                    # 描述评分
                    "descScore": item['descScore'],
                    # 物流评分
                    "logisticsScore": item['logisticsScore'],
                    # 服务评分
                    "serviceScore": item['serviceScore'],
                    # 订单号
                    "dingdanhao":item['orderSn'],
                    # 任务id
                    "task_id": task['id'],
                    # 任务状态
                    "state": "2",
                    # 店铺id
                    "shop_id": task['shop_id']
                }]
            }

            self.apiRequest( data )
        print('%s\t任务上传完成,等待下一次请求....'%task['id'])
    # API上传评价任务
    def apiRequest(self,data):

        try:

            r = requests.post(url=domain_url['return_comments_url'],data={"Post_Data": json.dumps(data)})

            if r.status_code == 200 and len(r.text) == 1 :

                print('%s\t订单号评价结果上传成功'%data['caijiwancheng'][0]['dingdanhao'])

            else:

                print('%s\t订单号评价结果上传失败' % data['caijiwancheng'][0]['dingdanhao'])

        except:

            # data['msg'] = '任务回置失败'
            Helper.writeErrorLog( json.dumps(data) )

    '''
    NameError
    ImportError
    IndexError
    '''


if __name__ == '__main__':

    c = PddComments()

    # c.obtainTask()
    print( c.requestIndex() )

    threads = []

